package com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.zhjd.common.util.ZhjdIotUtils;
import com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.entity.AsphaltPenetrometerEntity;
import com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.entity.AsphaltPenetrometerResEntity;
import com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.mapper.AsphaltPenetrometerMapper;
import com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.service.AsphaltPenetrometerResService;
import com.ruoyi.zhjd.laboratory.modules.asphaltPenetrometer.service.AsphaltPenetrometerService;
import com.ruoyi.zhjd.laboratory.modules.errorRecord.service.ErrorRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("asphaltPenetrometerService")
public class AsphaltPenetrometerServiceImpl extends ServiceImpl<AsphaltPenetrometerMapper, AsphaltPenetrometerEntity> implements AsphaltPenetrometerService {

    @Autowired
    private AsphaltPenetrometerMapper asphaltPenetrometerMapper;

    @Autowired
    private AsphaltPenetrometerResService asphaltPenetrometerResService;

//    @Autowired
//    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private ErrorRecordService errorRecordService;

    private static Map<String, String> currentMap = new HashMap<>();

    /**
     * 列表
     */
    @Override
    public IPage<JSONObject> queryPage(Map<String, Object> params) {
//        IPage<AsphaltPenetrometerEntity> page = baseServiceComponent.getPage(params, AsphaltPenetrometerEntity.class);
        return asphaltPenetrometerMapper.queryPage(null, params);
    }

    /**
     * 信息
     *
     * @return AsphaltPenetrometerEntity
     */
    @Override
    public AsphaltPenetrometerEntity getInfo(String id) {
        return getById(id);
    }

    /**
     * 保存
     */
    @Override
    public void saveData(AsphaltPenetrometerEntity asphaltPenetrometer) {
        save(asphaltPenetrometer);
    }

    /**
     * 修改
     */
    @Override
    public void updateData(AsphaltPenetrometerEntity asphaltPenetrometer) {
        updateById(asphaltPenetrometer);
    }

    /**
     * 删除单条数据
     *
     * @param id
     */
    @Override
    public void deleteOneData(String id) {
        removeById(id);
    }

    /**
     * 删除
     */
    @Override
    public void deleteData(List<String> ids) {
        removeByIds(ids);
    }

    /**
     * 解析沥青针入度仪数据
     *
     * @param resData  试验结果数据
     * @param deviceId 试验设备id
     */
    public void parsingData(String resData, String deviceId) {
        Date nowDate = new Date();
        try {
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(resData);
            //如果数据以00开头，可能设备刚开机或重启，表示一次新的实验开始
            if (StringUtils.equals(dataList.get(0), "00")) {
                currentMap.remove(deviceId);
            }
            //验证位不进行校验
            int i = 4;
            //试验数据
            if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_TEST, dataList.get(i))) {
                AsphaltPenetrometerEntity entity = new AsphaltPenetrometerEntity();
                entity.setDeviceId(deviceId);
                if (currentMap.get(deviceId) == null) {
                    AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
                    resEntity.setDeviceId(deviceId);
                    asphaltPenetrometerResService.save(resEntity);
                    currentMap.put(deviceId, resEntity.getId());
                }
                //设置实验结果数据id
                entity.setResId(currentMap.get(deviceId));

                entity.setOriginalData(resData);
                entity.setCreateTime(nowDate);
                i++;
                entity.setFlag(dataList.get(i));

                // 将16进制转换为10进制数据，不含（0x）
                // 实时位移
                i++;
                entity.setRealTimeDisplacement(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                // 实时温度
                i += 2;
                entity.setRealTimeTemperature(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                save(entity);
                //结果数据
            } else if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_RES, dataList.get(i))) {
                AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
                resEntity.setId(currentMap.get(deviceId));
                currentMap.remove(deviceId);
                resEntity.setDeviceId(deviceId);
                resEntity.setOriginalData(resData);
                resEntity.setCreateTime(nowDate);

                // 将16进制转换为10进制数据，不含（0x）
                // 实时位移
                i++;
                resEntity.setRealTimeDisplacement(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                // 实时温度
                i += 2;
                resEntity.setRealTimeTemperature(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                asphaltPenetrometerResService.saveOrUpdate(resEntity);
            } else {
                throw new ServiceException("针入度数据解析异常：" + resData);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, deviceId, resData);
            throw new ServiceException("数据解析异常");
        }
    }

    /**
     * 绑定材料
     *
     * @param asphaltPenetrometerResEntity
     */
    public void changeSample(AsphaltPenetrometerResEntity asphaltPenetrometerResEntity) {
        //更新试验结果表
        asphaltPenetrometerResService.updateById(asphaltPenetrometerResEntity);
        //查询试验过程数据
        List<AsphaltPenetrometerEntity> processList = list(new LambdaQueryWrapper<AsphaltPenetrometerEntity>().eq(AsphaltPenetrometerEntity::getResId, asphaltPenetrometerResEntity.getId()));
        if (CollectionUtil.isNotEmpty(processList)) {
            for (AsphaltPenetrometerEntity item : processList) {
                item.setSampleId(asphaltPenetrometerResEntity.getSampleId());
            }
            updateBatchById(processList);
        }
    }
}
